﻿using ScFramework.Core;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class Slime : MonoBehaviour
{
    public int BallCnt = 100;
    List<Ball> ballList = new List<Ball>();
    Color col = Color.white;
    Transform Texture;

    public void Init()
    {
        for(int i = 0; i < BallCnt; i++)
        {
            ballList.Add(ResourceManager.Instance.Instantiate("Prefabs/Ball", this.transform).GetComponent<Ball>());
            ballList.Last().GetComponent<Transform>().position=this.transform.position+new Vector3(Random.Range(-5,5),Random.Range(-5,5));
            ballList.Last().GetComponentInChildren<SpriteRenderer>().color = col;
        }
        Texture = GameObject.Find("MeshWithTextureFromCamera").transform;
    }
    public float alpha = 1;
    public float beta = 1;
    public float euler = 1;
    private void FixedUpdate()
    {
        var ctr = GetCenter();
            var vtr = ctr.normalized;
            var mag = ctr.magnitude;
            mag = Mathf.Pow(mag, beta);
        foreach(var x in ballList)
        {
            x.GetComponent<Rigidbody2D>().AddForce(-vtr*mag * alpha);
        }
    //    this.GetComponent<Rigidbody2D>().AddForce( vtr*mag * euler);
    }
    public Vector2 GetCenter()
    {
        Vector2 pos = Vector2.zero; ;
        foreach (var x in ballList)
        {
            pos += (Vector2)x.transform.localPosition;
        }
        pos /= ballList.Count;
        return pos;
    }
    public void SetCenter(Vector2 offset)
    {
        /*
        Vector2 pos = Vector2.zero; ;
        foreach(var x in ballList)
        {
            pos +=(Vector2) x.transform.localPosition;
        }
        pos /= ballList.Count;
        */
        foreach(var x in ballList)
        {
            x.transform.localPosition = new Vector2(Random.Range(-5, 5), Random.Range(-5, 5)) + offset;
            x.GetComponent<Rigidbody2D>().velocity = Vector2.zero;
        }
    }
    public void SetColor(Color c)
    {
        col = c;
        if (Texture == null)
        {
            Texture = GameObject.Find("MeshWithTextureFromCamera").transform;
        }
        //    var a = Texture.GetComponent<MeshRenderer>().sharedMaterial.GetColorArray();
      //  foreach
        Texture.GetComponent<MeshRenderer>().sharedMaterial.SetColor("_StrokeColor", c) ;
        c = new Color(c.r *0.8f, c.g *0.8f, c.b *0.8f, c.a);
        Texture.GetComponent<MeshRenderer>().sharedMaterial.color = c;
        //   CameraManager.Instance.eCamera.GetComponent<BlurController>().blurShader.
        /*foreach(var x in ballList)
        {
            x.GetComponentInChildren<SpriteRenderer>().color = c;
        }*/
    }
}
